<?php

namespace app\admin\controller\manager;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Loader;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class User extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model            = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'uid';


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $platform = session("admin")["platform"];//1:zong,2:shang

        $uid = session("admin")["id"];
        $_where = [];
        if($uid!=6){
            if ($platform == 2) {
                $this->childrenAdminIds = $this->auth->getChildrenBussinessAdminIds(true);
                $this->childrenGroupIds = $this->auth->getChildrenBusinessGroupIds(true, 8);
            }else{
                $this->childrenAdminIds = $this->auth->getChildrenPlaAdminIds(true);
                $this->childrenGroupIds = $this->auth->getChildrenBusinessGroupIds(true, 12);
            }
        }else {
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        }
        $groupList = collection(Db::name("auth_group")->where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                if($v["pid"]!=8) {
                    $groupdata[$v['id']] = $v['name'];
                }
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;

        }
        if($platform!=2) {
            unset($groupdata[6]);
        }
        $admin_info = session("admin");
        //halt($admin_info);
        $this->view->assign('groupdata', $groupdata);
        $this->view->assign('platform',$platform);
        $this->view->assign('admin_info',$admin_info);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if(session("admin")["athur_id"]==0) {
                $_where["a.athor"] = session("admin")["id"];
            }elseif(session("admin")["athur_id"]==1){
                $_where["a.athor"] = session("admin")["athor"];
            }
            $join[] = ["auth_group_access group_access", "a.id = group_access.uid"];
            $join[] = ["auth_group g", "g.id = group_access.group_id"];
            $field  = "a.id,a.username,a.nickname,a.status status,a.createtime ,a.role,g.pid,g.name,a.platform";
            $total  = Db::name('admin')->alias("a")->join($join)->field($field)->where($_where)->where($where)->count();
            $list   = Db::name('admin')->alias("a")->join($join)->field($field)->where($_where)->where($where)->limit($offset, $limit)->order("createtime DESC")->select();
            //echo Db::name('admin')->getLastSql();exit;
            foreach ($list as &$value) {
                if ($value['platform'] == 1) {
                    $value['platform'] = '总管理后台';
                }
                if ($value['platform'] == 2) {
                    $value['platform'] = '商户后台';
                }
                if ($value['status'] === 'normal') {
                    $value['status'] = '正常';
                } else {
                    $value['status'] = '禁用';
                }
                $value['g.name'] = $value['name'];
                $value["a.createtime"] = $value["createtime"];
                $value["a.status"] = $value["status"];
            }
            //dump($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //halt(session("admin"));
                if (preg_match("/[\x7f-\xff]/", $params["username"])) {
                    $this->error("不能输入中文！");
                }
                if(!preg_match("/^1[34578]\d{9}$/", $params["mobile"])){
                    //验证通过
                    return json(['code' => 0, 'msg' => '手机格式有问题!']);
                }
                if(strlen($params["username"])<3 || strlen($params["username"])>12){
                    return json(['code' => 0, 'msg' => '请输入3-12位数字或字符!']);
                }
                if(strlen($params["password"])<6){
                    return json(['code' => 0, 'msg' => '密码位数不能小于6!']);
                }
                $params['salt']     = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar']   = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $params['email'] = '';
                $params["athor"] = session("admin")["id"];

                $group = $this->request->post("group/a");
                if(session("admin")["platform"]==2){
                    $params["athur_id"] = 1;
                }else{
                    if($params['platform'] == 1 && $group[0]==8){
                        $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
                    }
                    if($params['platform'] == 2 && $group[0]!=8){
                        $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
                    }
                }
//                else{
////                    $this->childrenAdminIds = $this->auth->getChildrenBussinessAdminIds(true);
////                    $this->childrenGroupIds = $this->auth->getChildrenBusinessGroupIds(true, 8);
////                    $groupList = collection(Db::name("auth_group")->where('id', 'in', $this->childrenGroupIds)->select())->toArray();
////                    Tree::instance()->init($groupList);
////                    $groups = $this->auth->getGroups();
////                    foreach ($groups as $m => $n) {
////                        $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
////                        $temp = [];
////                        foreach ($childlist as $k => $v) {
////                            $temp[$v['id']] = $v['name'];
////                        }
////                        $result[__($n['name'])] = $temp;
////                    }
////                    $groupdata = $result;
////
////                    if($params['platform'] == 1){
////                        if (in_array($group[0], $this->childrenGroupIds)) {
////                            $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
////                        }
////                    }
////                    if($params['platform'] == 2){
////                        if (!in_array($group[0], $this->childrenGroupIds)) {
////                            $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
////                        }
////                    }
////                    if($params['platform'] == 2) {
////                        if ($group[0] != 8) {
////                            if (in_array($group[0], $this->childrenGroupIds)) {
////                                $this->error('平台不可以添加商家子类！');
////                            }
////                        }
////                    }
//
//                }
                //这里需要针对username和email做唯一验证
                //$adminValidate = \think\Loader::validate('Admin');
                if ($params['platform'] == 2) {

                    if(empty($params['bank_name'])){
                        $this->error('开户行名称不能为空');
                    }
                    if(empty($params['bank_username'])){
                        $this->error('开户人名字不能为空');
                    }
                    if(empty($params['bank_account'])){
                        $this->error('开户行账号不能为空');
                    }
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|max:50|unique:admin,username',
                    'mobile'    => 'require|unique:admin,mobile',
                ]);
                $result = $this->model->validate('Admin.add')->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                //dump($group);
                //过滤不允许的组别,避免越权
                $group   = array_intersect($this->childrenGroupIds, $group);

                //dump($group);
                //exit;
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                if($params['platform']==2) {
                    $shop_admin_wallet = Db::name("shop_admin_wallet")->where('admin_id', $this->model->id)->find();
                    if (!$shop_admin_wallet) {
                        $shop_admin_wallet_data = [
                            "admin_id" => $this->model->id,
                            "balance" => 0.00,
                            "create_time" => time(),
                            "update_time" => time(),
                            "frozen_money" => 0.00
                        ];
                        Db::name("shop_admin_wallet")->insert($shop_admin_wallet_data);
                    }
                }
                $this->success();
            }
            $this->error();
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (preg_match("/[\x7f-\xff]/", $params["username"])) {
                    $this->error("不能输入中文！");
                }
//                if(!preg_match("/^1[34578]\d{9}$/", $params["mobile"])){
//                    //验证通过
//                    return json(['code' => 0, 'msg' => '手机格式有问题!']);
//                }
                if ($params['password']) {
                    $params['salt']     = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }

                $group = $this->request->post("group/a");
                if(session("admin")["platform"]==2){
                    $params["athur_id"] = 1;
                }else{
                    if($params['platform'] == 1 && $group[0]==8){
                        $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
                    }
                    if($params['platform'] == 2 && $group[0]!=8){
                        $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
                    }
                }
//                else{
//                    $this->childrenAdminIds = $this->auth->getChildrenBussinessAdminIds(true);
//                    $this->childrenGroupIds = $this->auth->getChildrenBusinessGroupIds(true, 8);
//
//                    halt($this->childrenGroupIds);
//
//                    if($params['platform'] == 1){
//                        //if ($group[0] != 8) {
//                        if (in_array($group[0], $this->childrenGroupIds)) {
//                            $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
//                        }
//                        // }
//                    }
//                    if($params['platform'] == 2){
//                        //if ($group[0] != 8) {
//                        if (!in_array($group[0], $this->childrenGroupIds)) {
//                            $this->error('商家只能是商户权限组；平台添加平台权限组相关的！');
//                        }
//                        // }
//                    }
//                    if($params['platform'] == 2) {
//                        if ($group[0] != 8) {
//                            if (in_array($group[0], $this->childrenGroupIds)) {
//                                $this->error('平台不可以添加商家子类！');
//                            }
//                        }
//                    }
//                }

                //echo $row->id;exit;
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                //echo "aaa";exit;
                $adminValidate->rule([
                    'username' => 'require|max:50|unique:admin,username,' . $row->id,
                    'mobile'    => 'require|unique:admin,mobile,' . $row->id,
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();

                //$group = $this->request->post("group/a");

//                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                //halt($this->model);
                if($params['platform']==2) {
                    $shop_admin_wallet = Db::name("shop_admin_wallet")->where('admin_id', $row->id)->find();
                    if (!$shop_admin_wallet) {
                        $shop_admin_wallet_data = [
                            "admin_id" => $row->id,
                            "balance" => 0.00,
                            "create_time" => time(),
                            "update_time" => time(),
                            "frozen_money" => 0.00
                        ];
                        Db::name("shop_admin_wallet")->insert($shop_admin_wallet_data);
                    }
                }
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids  = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $platform = $row["platform"];
        $this->view->assign("platform",$platform);
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList        = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    protected function selectpage()
    {
        $this->dataLimit      = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

    /**
     * 密码重置
     * @Author   chenjianghui
     * @DateTime 2018-09-03T14:14:42+0800
     * @return   [type]                   [description]
     */
    public function resetpsw($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params['password']) {
                $params['salt']     = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            } else {
                unset($params['password'], $params['salt']);
            }
            $result = $row->save($params);
            if ($result !== false) {
                return json(['code' => 1, 'msg' => '密码重置成功']);
                renderJson("密码重置成功", 1);
            } else {
                return json(['code' => 0, 'msg' => '密码重置失败']);
                renderJson("密码重置失败", 0);
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 状态更改
     */
    public function update_status()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            //dump($params);die;
            $status = "";
            if ($params) {
                switch ($params["field"]) {
                    case "status":
                        $status = $params["status"] == '正常' ? 'hidden' : 'normal';
                        break;
                }
                try {
                    $res = $this->model->save([$params["field"] => $status], ["id" => $params["id"]]);
                    renderJson("成功", 1);
                } catch (\Exception $e) {
                    renderJson("失败", 0);
                }

            }
        }
    }

}
